/**
* 版权所有：福建邮科电信业务部厦门研发中心 
*====================================================
* 文件名称: ExportXlsSupport.java
* 修订记录：
* No    日期				作者(操作:具体内容)
* 1.    Jun 16, 2012			詹保山(softzbs@126.com)(创建:创建文件)
*====================================================
* 类描述：(说明未实现或其它不应生成javadoc的内容)
* 
*/
package com.devframe.web.handle;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;

import net.sf.jxls.transformer.XLSTransformer;

import com.devframe.web.MyContext;
import com.devframe.web.MyStatics;

/**
 *<pre><b><font color="blue">ExportXlsSupport</font></b></pre>
 *
 *<pre><b>&nbsp;--描述说明--</b></pre>
 * <pre>对导出EXCEL文件的支持</pre>
 * <pre>
 * <b>--样例--</b>
 *   ExportXlsSupport obj = new ExportXlsSupport();
 *   obj.method();
 * </pre>
 */
public class ExportXlsResultHandle {
	
	private static final Logger LOG = Logger.getLogger(ExportXlsResultHandle.class);
	/**
	 * 获取导出文件模板
	 * @param context
	 * @param templateFileName
	 * @return
	 * @author:詹保山
	 */
	private String getTemplateFile(MyContext context,String templateFileName){
		   String exportFileName = context.getParameter(MyStatics.PARAM_EXPORT_XLS_FILE_NAME);
	        if (exportFileName == null || exportFileName.equals("")) {
	            exportFileName = templateFileName;
	            if (exportFileName.lastIndexOf("/") > 0) {
	                exportFileName = exportFileName.substring(exportFileName.lastIndexOf("/") + 1);
	            }
	        }
	        return exportFileName;
	}
	/**
	 * 整理导出的数据
	 * @param data
	 * @return
	 * @author:詹保山
	 */
	private Map<String,Object>  getExportDatas(Object data){
		//如果是MAP 直接转为MAP 并返回
		 if(data instanceof Map){
			 return (Map<String,Object>)data; 
		 }
		 //如果是非MAP结构，则将获取对象的get的方法，并为改方法名去掉get前缀 将首字母变为小写作为KEY ，其值作为VALUE
		 Map<String,Object> dataMap=new HashMap<String, Object>();
         Method[] methods = data.getClass().getMethods();
         for (int i = 0; i < methods.length; i++) {
             Method getMethod = methods[i];
             if (getMethod.getName().indexOf("get") == 0 && getMethod.getParameterTypes().length == 0) {
                 String fieldName = getMethod.getName().substring(3);
                 fieldName = StringUtils.uncapitalize(fieldName);
                 Object fieldValue;
                 try {
                     fieldValue = getMethod.invoke(data, new Object[0]);
                     dataMap.put(fieldName, fieldValue);
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
             }
         }
		 return dataMap;
	}
	public void execute(MyContext context,HttpServletResponse response,Object data,String templateFileName){
		   String exportFileName = this.getTemplateFile(context, templateFileName);
	        InputStream is;
	        try {
	            is = new BufferedInputStream(new FileInputStream(context.getRootPath() + templateFileName));
	        } catch (FileNotFoundException e1) {
	            LOG.error("导出模板文件不存在:" + templateFileName);
	            e1.printStackTrace();
	            return;
	        }
	        // 将action中的属性转成map的键值
	        Map dataMap = this.getExportDatas(data);
		    XLSTransformer transformer = new XLSTransformer();
	        Workbook workBook = null;
	        // 导出
	        try {
	            workBook = transformer.transformXLS(is, dataMap);
	            response.setContentType("application/msexcel;charset=utf-8");
	            response.setHeader("Content-Disposition", "attachment; filename=\""
	            		+ java.net.URLEncoder.encode(exportFileName, "UTF-8"));
	            OutputStream out;
	            out = response.getOutputStream();
	            workBook.write(out);
	            out.flush();
	        } catch (Throwable e) {
	            LOG.error("导出EXCEL出错：" + e.getLocalizedMessage());
	            e.printStackTrace();
	        } finally {
	            try {
	                is.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	}
	

}
